<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;

class Jianuo extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $data = [
            'Service'=>'SubmitOrder',
            'BizType'=>'ECARD',
            'UserId'=>$bean->getSupplierNum(),
            'ProductId'=>$bean->getGoodsId(),
            'AccountVal'=>$bean->getAccount(),
            'BuyNum'=> $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'OrderNo'=>$bean->getOrderNo(),//订单号
            'Time'=>time(),
        ];
        $data['Sign'] = $this->sign($data,$bean->getSecretKey());
        return $data;
    }
    /**
     * @param $array
     * @param $key
     * @return string
     */
    public function sign($array,$key): string
    {
        ksort($array);
        $concatenatedString = implode('', array_map(function ($key, $value) {
            return $key . $value;
        }, array_keys($array), $array));
       return md5($concatenatedString . $key);
    }


    /**
     * @inheritDoc
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('OrderStatus', '');
        $order_sn = $request->input('OrderNo', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['SUCCESS', 'FAILED']))->setRechargeSuccess($status == 'SUCCESS');

    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return array|mixed
     */
    public function balance(InterfaceConfiguration $config, BasicInformation $bean){
        $array = [
            'Service'=>'QueryBalance',
            'UserId'=>$bean->getSupplierNum(),
            'BizType'=>'ECARD',
            'Time'=>time(),
        ];
        $array['Sign'] =  $this->sign($array,$bean->getSecretKey());
        $curl =  httpClient()->post($config -> balance_url, $array)->json();
        return (data_get($curl, $config->balance_title, 0)/100);
    }
    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('{“code”: 0}');
    }
}
